package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        //地址为空
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook==null){
            throw  new AddressBookBusinessException("收获地址是空的，请设置地址！");
        }
        //查询当前用户购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(user.getId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        //购物车为空
        if (shoppingCarts==null || shoppingCarts.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setNumber(UUID.randomUUID().toString());   //订单号
        order.setStatus(Orders.PENDING_PAYMENT);        //订单状态
        order.setUserId(BaseContext.getCurrentId());    //下单用户id
        order.setOrderTime(LocalDateTime.now());       //下单时间
        order.setCheckoutTime(LocalDateTime.now());    //结账时间
        order.setPayStatus(Orders.UN_PAID);            //支付状态
        //用户信息
        order.setUserName(user.getName()) ;            //用户名
        order.setPhone(addressBook.getPhone());        //手机号
        order.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName());
        order.setConsignee(addressBook.getConsignee()); //收货人
        //插入数据到订单表(id回显)
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }
        //插入n个订单明细数据
        orderDetailMapper.insertBatch(orderDetails);

        //清除购物车
        shoppingCartMapper.deleteByUserId(user.getId());
        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId()).orderNumber(order.getNumber())
                .orderAmount(order.getAmount()).orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付、修改状态
     * @param ordersPaymentDTO
     */
    public void payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //发送来电提醒
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment2(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getUserById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 查询历史订单
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        Orders o = Orders.builder().userId(BaseContext.getCurrentId()).build();
        BeanUtil.copyProperties(dto,o);
        //设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<OrderVO> p =new Page<>();
        //条件分页查询Orders
        List<Orders> orders = orderMapper.getOrders(o);
        for (Orders order : orders) {
            List<OrderDetail> orderDetails=orderDetailMapper.getByOrder(order);
            OrderVO orderVO = new OrderVO();
            BeanUtil.copyProperties(order,orderVO);
            orderVO.setOrderDetailList(orderDetails);
            p.add(orderVO);
        }
        //封装PageResult
        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
        return pageResult;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        Orders o = Orders.builder().id(id).build();
        List<Orders> orders = orderMapper.getOrders(o);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrder(orders.get(0));
        //封装
        OrderVO orderVO = new OrderVO();
        BeanUtil.copyProperties(orders.get(0),orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders order = Orders.builder().id(id).status(Orders.CANCELLED).build();
        orderMapper.update(order);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Orders order = Orders.builder().id(id).build();
        //查询当前订单信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrder(order);
        //加入购物车
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            //用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtil.copyProperties(orderDetail,shoppingCart);
            //插入数据到购物车
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 订单搜索
     * @param dto
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        //设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //条件分页查询
        Page<OrderVO> p = new Page<>();

        dto.setUserId(BaseContext.getCurrentId());
        //条件查询所有订单
        Page<Orders> orders = (Page<Orders>) orderMapper.getByDto(dto);
        for (Orders order1 : orders) {
            //封装OrderVO:order+orderDishes
            OrderVO orderVO = new OrderVO();
            BeanUtil.copyProperties(order1,orderVO);
            //订单详情(获取菜名)
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrder(order1);
            StringJoiner orderDishes=new StringJoiner(",");
            for (OrderDetail orderDetail : orderDetails) {
                orderDishes.add(orderDetail.getName());
            }
            orderVO.setOrderDishes(orderDishes.toString());

            p.add(orderVO);
        }
        PageResult pageResult = new PageResult(orders.getTotal(), p.getResult());
        return pageResult;
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        List<OrderStatus> orderStatus=orderMapper.statistics();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        for (OrderStatus oStatus : orderStatus) {
            Integer status = oStatus.getStatus();
            Integer sum = oStatus.getSum();
            //待接单
            if (status==Orders.TO_BE_CONFIRMED){
                orderStatisticsVO.setToBeConfirmed(sum);
            }
            //待派送
            if (status==Orders.CONFIRMED){
                orderStatisticsVO.setConfirmed(sum);
            }
            //派送中
            if (status==Orders.DELIVERY_IN_PROGRESS){
                orderStatisticsVO.setDeliveryInProgress(sum);
            }
        }
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //获取当前接单 订单
        Orders order = Orders.builder().id(ordersConfirmDTO.getId()).userId(BaseContext.getCurrentId()).build();
        List<Orders> orders = orderMapper.getOrders(order);
        //修改状态为:已接单
        orders.get(0).setStatus(Orders.CONFIRMED);
        orderMapper.update(orders.get(0));
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .userId(BaseContext.getCurrentId()).build();
        orderMapper.update(order);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders order = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .userId(BaseContext.getCurrentId()).build();
        orderMapper.update(order);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders order = Orders.builder().id(id).userId(BaseContext.getCurrentId())
                .status(Orders.DELIVERY_IN_PROGRESS)
                .deliveryTime(LocalDateTime.now().plusHours(1L)).build();
        orderMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders order = Orders.builder().id(id).status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(order);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders o = Orders.builder().userId(BaseContext.getCurrentId()).id(id).build();
        List<Orders> orders = orderMapper.getOrders(o);
        if (orders.get(0) == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //催单:发送提醒
        Map map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",id);
        map.put("content","订单号:"+orders.get(0).getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}















